//
//  ChatViewController.m
//  WeChat
//
//  Created by wangcarl on 16/8/31.
//  Copyright © 2016年 wangcarl. All rights reserved.
//

#import "ChatViewController.h"

@interface ChatViewController ()<NSFetchedResultsControllerDelegate,UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
{
    NSFetchedResultsController *_resultController;
}
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomConstraint;



@end

@implementation ChatViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSManagedObjectContext *msgContext=[XMPPTool sharedXMPPTool].msgArchivingStorage.mainThreadManagedObjectContext;
    NSFetchRequest *request=[NSFetchRequest fetchRequestWithEntityName:@"XMPPMessageArchiving_Message_CoreDataObject"];
    
    NSString *localJID=[XMPPTool sharedXMPPTool].xmppStream.myJID.bare;
    NSPredicate *pre=[NSPredicate predicateWithFormat:@"streamBareJidStr = %@ AND bareJidStr = %@",localJID,self.friendJid.bare];
    
    request.predicate=pre;
    NSSortDescriptor *sort=[NSSortDescriptor sortDescriptorWithKey:@"timestamp" ascending:YES];
    request.sortDescriptors =@[sort];
    _resultController=[[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:msgContext sectionNameKeyPath:nil cacheName:nil];
    
    _resultController.delegate=self;
    NSError *error=nil;
    [_resultController performFetch:&error];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(kbWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(kbWillHide:) name:UIKeyboardWillHideNotification object:nil];

    
    
    
    // Do any additional setup after loading the view.
}
-(void)kbWillShow:(NSNotification *)noti{
    //显示的时候改变bottomContraint
    
    // 获取键盘高度
    NSLog(@"%@",noti.userInfo);
    CGFloat kbHeight = [noti.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    
    
    self.bottomConstraint.constant = kbHeight;
}


#pragma mark 键盘将隐藏
-(void)kbWillHide:(NSNotification *)noti{
    self.bottomConstraint.constant = 0;
    
}

-(void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
    [self.tableView reloadData];
    NSIndexPath *lastIndex=[NSIndexPath indexPathForRow:_resultController.fetchedObjects.count inSection:0];
    [self.tableView scrollToRowAtIndexPath:lastIndex atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _resultController.fetchedObjects.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *ID=@"ChatCell";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:ID];
    XMPPMessageArchiving_Message_CoreDataObject *msgObj=_resultController.fetchedObjects[indexPath.row];
    cell.textLabel.text=msgObj.body;
    return cell;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    NSString *text=self.textField.text;
    XMPPMessage *msg=[XMPPMessage messageWithType:@"chat" to:self.friendJid];
    
    [msg addBody:text];
    [[XMPPTool sharedXMPPTool].xmppStream sendElement:msg] ;
    
    return YES;
}
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
